<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 左侧装饰 -->
      <div class="login-left">
        <div class="login-left-content">
          <h2 class="welcome-text">欢迎使用</h2>
          <h1 class="system-name">智护童行</h1>
          <div class="decoration-image">
            <el-image src="https://cdn.pixabay.com/photo/2017/01/31/21/23/avatar-2027366_1280.png" fit="contain" />
          </div>
        </div>
      </div>
      <!-- 右侧登录表单 -->
      <div class="login-right">
        <div class="login-form-container">
          <h2 class="text-center mb-4">用户登录</h2>
          <el-form 
            ref="loginForm" 
            :model="form" 
            :rules="rules" 
            class="login-form"
            @keyup.enter="handleLogin"
          >
            <el-form-item class="role-select">
              <el-radio-group v-model="form.role" size="large">
                <el-radio-button label="user">普通用户</el-radio-button>
                <el-radio-button label="expert">专家用户</el-radio-button>
                <el-radio-button label="admin">管理员</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="username">
              <el-input 
                v-model="form.username"
                placeholder="请输入用户名"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="form.password"
                type="password"
                placeholder="请输入密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <div class="remember-forgot">
              <el-checkbox v-model="form.remember">记住我</el-checkbox>
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>
            <el-form-item>
              <el-button type="primary" class="w-100" :loading="loading" @click="handleLogin">
                登录
              </el-button>
            </el-form-item>
            <div class="register-link text-center">
              <span class="text-muted">还没有账号？</span>
              <el-link type="primary" :underline="false" @click="showRegisterDialog">立即注册</el-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="400px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
        class="register-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="registering" @click="handleRegister">
            注册
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { userLogin, expertLogin, register } from '@/api/user'
import { adminLogin } from '@/api/admin'
import { setToken, parseToken } from '@/utils/auth'
import router from '@/router'

const loginForm = ref(null)
const form = ref({
  username: '',
  password: '',
  remember: false,
  role: 'user' // 默认选择普通用户
})

const loading = ref(false)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginForm.value) return
  
  try {
    const valid = await loginForm.value.validate()
    if (valid) {
      loading.value = true
      
      // 根据选择的角色使用对应的登录API
      let loginApi
      switch (form.value.role) {
        case 'expert':
          loginApi = expertLogin
          break
        case 'admin':
          loginApi = adminLogin
          break
        default:
          loginApi = userLogin
      }
      
      // 调用对应的登录API
      const res = await loginApi({
        username: form.value.username,
        password: form.value.password
      })
      
      // 打印原始token
      console.log('登录成功，获取到的token:', res.token)
      
      // 保存token
      setToken(res.token)
      
      // 解析token内容
      const tokenInfo = parseToken(res.token)
      console.log('token解析结果:', {
        用户ID: tokenInfo.id,
        用户名: tokenInfo.username,
        用户类型: tokenInfo.userType,
        过期时间: new Date(tokenInfo.exp * 1000).toLocaleString()
      })
      
      // 根据token中的用户类型设置角色
      localStorage.setItem('userRole', tokenInfo.userType)
      console.log('设置用户角色:', tokenInfo.userType)
      
      ElMessage.success('登录成功')
      
      // 如果记住密码，保存用户名
      if (form.value.remember) {
        localStorage.setItem('rememberedUsername', form.value.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }
      
      // 根据用户类型跳转
      const userType = tokenInfo.userType
      console.log('用户类型:', userType)
      
      try {
        if (userType === 'admin') {
          console.log('准备跳转到管理后台')
          await router.push('/admin/dashboard')
        } else if (userType === 'expert') {
          console.log('准备跳转到专家工作台')
          await router.push('/expert/consultation')
        } else {
          console.log('准备跳转到用户首页')
          await router.push('/user/home')
        }
        console.log('路由跳转完成')
      } catch (error) {
        console.error('路由跳转失败:', error)
      }
    }
  } catch (error) {
   
  } finally {
    loading.value = false
  }
}

// 初始化时，如果有记住的用户名则填充
if (localStorage.getItem('rememberedUsername')) {
  form.value.username = localStorage.getItem('rememberedUsername')
  form.value.remember = true
}

// 注册相关
const registerDialogVisible = ref(false)
const registerFormRef = ref(null)
const registering = ref(false)

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: ''
})

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ]
}

// 显示注册对话框
const showRegisterDialog = () => {
  registerDialogVisible.value = true
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registering.value = true
      try {
        await register({
          username: registerForm.value.username,
          password: registerForm.value.password,
          phone: registerForm.value.phone
        })
        ElMessage.success('注册成功，请登录')
        registerDialogVisible.value = false
        // 自动填充登录表单
        form.value.username = registerForm.value.username
        form.value.password = ''
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error(error.message || '注册失败')
      } finally {
        registering.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
  margin: 0;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  will-change: transform;
  -webkit-font-smoothing: antialiased;
}

.login-box {
  width: 80%;
  max-width: 1200px;
  height: 80%;
  max-height: 700px;
  min-height: 500px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  display: flex;
  overflow: hidden;
  animation: fadeIn 0.5s ease-out;
  will-change: transform, opacity;
  transform: translateZ(0);
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  position: relative;
}

.login-left-content {
  text-align: center;
  z-index: 1;
}

.welcome-text {
  font-size: 24px;
  margin-bottom: 10px;
  opacity: 0;
  animation: slideUp 0.5s ease-out forwards;
  animation-delay: 0.2s;
}

.system-name {
  font-size: 32px;
  margin-bottom: 30px;
  opacity: 0;
  animation: slideUp 0.5s ease-out forwards;
  animation-delay: 0.4s;
}

.decoration-image {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  opacity: 0;
  animation: slideUp 0.5s ease-out forwards;
  animation-delay: 0.6s;
  will-change: transform, opacity;
}

.decoration-image :deep(img) {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

.login-right {
  flex: 1;
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form-container {
  width: 100%;
  max-width: 400px;
  padding: 0 20px;
}

.login-form {
  width: 100%;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 25px;
}

.login-form :deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 1px 15px;
  height: 45px;
  background-color: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--primary-color) !important;
  background-color: #fff;
}

.login-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.login-form :deep(.el-input__inner) {
  height: 45px;
  line-height: 45px;
  font-size: 14px;
}

.login-form :deep(.el-input__prefix) {
  font-size: 18px;
  color: #909399;
}

.login-form :deep(.el-form-item__error) {
  padding-top: 4px;
  font-size: 13px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: -10px 0 20px;
}

.login-form :deep(.el-checkbox__label) {
  font-size: 14px;
  color: #606266;
}

.login-form :deep(.el-button) {
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-form :deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
}

.register-link {
  margin-top: 20px;
}

.register-link .text-muted {
  color: #909399;
  font-size: 14px;
  margin-right: 5px;
}

.register-link :deep(.el-link) {
  font-size: 14px;
  font-weight: 500;
}

.role-select {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.role-select :deep(.el-radio-group) {
  width: 100%;
  display: flex;
  gap: 10px;
}

.role-select :deep(.el-radio-button) {
  flex: 1;
}

.role-select :deep(.el-radio-button__inner) {
  width: 100%;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    flex-direction: column;
    height: auto;
    width: 100%;
    max-width: 500px;
  }

  .login-left {
    padding: 30px;
  }

  .login-right {
    padding: 30px;
  }

  .decoration-image {
    width: 200px;
    height: 200px;
  }
}

.register-form {
  padding: 20px 0;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style> 